package com.yuke.cloud.service.smc.service.impl;

import com.alibaba.fastjson.JSON;
import com.yuke.cloud.common.base.constant.MQConstants;
import com.yuke.cloud.common.base.enums.ErrorCodeEnum;
import com.yuke.cloud.common.core.mq.RabbitMetaMessage;
import com.yuke.cloud.common.core.mq.RabbitSender;
import com.yuke.cloud.common.core.support.BaseService;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.opc.dto.UploadFile;
import com.yuke.cloud.service.api.opc.exceptions.OpcBizException;
import com.yuke.cloud.service.api.opc.service.OpcFileFeignApi;
import com.yuke.cloud.service.api.opc.service.OpcGaodeFeignApi;
import com.yuke.cloud.service.api.pmc.dto.ProdSpecInfoDto;
import com.yuke.cloud.service.api.pmc.exceptions.PmcBizException;
import com.yuke.cloud.service.api.pmc.service.PmcFeignApi;
import com.yuke.cloud.service.api.smc.dto.GoodsAndSpecInfoDto;
import com.yuke.cloud.service.api.smc.dto.ShopCartInfoDto;
import com.yuke.cloud.service.api.smc.dto.ShopInfoDto;
import com.yuke.cloud.service.api.smc.dto.SmcShopDto;
import com.yuke.cloud.service.api.uac.dto.UserInfoDto;
import com.yuke.cloud.service.api.uac.exceptions.UacBizException;
import com.yuke.cloud.service.api.uac.service.UacUserFeignApi;
import com.yuke.cloud.service.api.wmc.service.WmcStorageFeignApi;
import com.yuke.cloud.service.smc.dao.DmsStoreMapper;
import com.yuke.cloud.service.smc.dao.ShopMapper;
import com.yuke.cloud.service.smc.dto.ShopDto;
import com.yuke.cloud.service.smc.dto.StoreShopDto;
import com.yuke.cloud.service.smc.entity.DmsStore;
import com.yuke.cloud.service.smc.entity.ExcelObject;
import com.yuke.cloud.service.smc.entity.Shop;
import com.yuke.cloud.service.smc.entity.ShopAuditLog;
import com.yuke.cloud.service.smc.exceptions.SmcBizException;
import com.yuke.cloud.service.smc.service.ShopAuditLogService;
import com.yuke.cloud.service.smc.service.ShopService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


/**
 * Created by wg on 2018/09/07.
 */
@Import(RabbitSender.class)
@Slf4j
@Service
@Transactional
public class ShopServiceImpl extends BaseService<Shop> implements ShopService {
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private OpcGaodeFeignApi opcGaodeFeignApi;
    @Resource
    private PmcFeignApi pmcFeignApi;
    @Resource
    private UacUserFeignApi uacUserFeignApi;
    @Resource
    private OpcFileFeignApi opcFileFeignApi;
    @Autowired
    private RabbitSender rabbitSender;

    @Autowired
    private ShopAuditLogService shopAuditLogService;
    @Resource
    private WmcStorageFeignApi wmcStorageFeignApi;
    @Resource
    private DmsStoreMapper dmsStoreMapper;





    @Override
    public int save(Shop record) {
        log.info("--- shop save begin:{} ---", record);

        // add by wg 20190805 增加判断，是否有店铺正在审核中，如果有则直接返回
        Shop shopApply = new Shop();
        shopApply.setUserId(record.getUserId());
        shopApply.setCreateStatus((byte)1);
        int applyCount = super.selectCount(shopApply);
        if (applyCount > 0) {
            log.info("--- 店铺已经在申请中 ---");
            return -3;
        }

        Shop shop = this.getLatitudeAndLongitude(record);
        if (shop == null) {
            log.info("--- region is null or error address ---");
            return -1;
        }

        // mod by wg 20190626 先判断该用户下是否有店铺且未审核通过的，如果有则更新
        Shop shopTemp = new Shop();
        shopTemp.setUserId(shop.getUserId());
        shopTemp.setCreateStatus((byte)3);
        int num = super.selectCount(shopTemp);
        int count = 0;
        if (num == 1) {
            shop.setCreateStatus((byte)1);
            shop.setUpdateTime(new Date());
            Example example = new Example(Shop.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", shop.getUserId());
            count = shopMapper.updateByExampleSelective(shop, example);
        } else if (num == 0) {
            /**************
             原程序
             ***********************/

            //todo 2019-12-06 让店铺注册后审核
            if(shop.getShopType() == null || shop.getShopType().equals((byte)1)){
                shop.setShopId(generateId());
                count = super.save(shop);
                getShopIdToStore(shop);

            }else {
                //todo 2019-12-06 让云顶商人注册后不必审核
                shop.setCreateStatus((byte) 2);
                shop.setRunStatus((byte) 1);
                shop.setShopId(generateId());
                count = super.save(shop);


                //todo 2019-12-06 让店铺绑定仓库
                SmcShopDto smcShopDto = new SmcShopDto();
                BeanUtils.copyProperties(shop, smcShopDto);
                wmcStorageFeignApi.bindWarehouseShop(smcShopDto);

                //todo 2019-12-06   完成审核记录
                ShopAuditLog shopAuditLog = new ShopAuditLog();
                shopAuditLog.setShopId(shop.getShopId());
                shopAuditLog.setAdminId(1L);
                shopAuditLog.setAuditType((byte) 1);
                shopAuditLog.setShopAuditId(generateId());
                shopAuditLog.setResult((byte) 1);
                shopAuditLog.setMessage("系统自动审核");
                shopAuditLogService.save(shopAuditLog);
            }
            //添加店铺收获地址
            ShopInfoDto shopInfoDto = new ShopInfoDto();
            BeanUtils.copyProperties(shop,shopInfoDto);
            uacUserFeignApi.saveUserDeliveryAddress(shopInfoDto);


        } else if (num > 1) {
            return -2;
        }
        log.info("--- shop save end:{} ---", shop);

        if (count > 0 && (record.getCreateStatus() == null || record.getCreateStatus() == 1)){
            this.shopReviewMessage(record.getShopId());
        }

        return count;
    }

    @Override
    public List<Shop> getListByCondition(Shop shop) {
        return shopMapper.getListByCondition(shop);
    }

    private void shopReviewMessage(Long shopId) {
        log.info("--- Enter shopReviewMessage(Long shopId)，参数：{} ---", shopId);
        Map map = new HashMap();
        map.put("MessageType", "shopReview");
        map.put("body", "通知店铺管理员，有店铺申请需要审核");
        RabbitMetaMessage rabbitMetaMessage = new RabbitMetaMessage();
        rabbitMetaMessage.setExchange(MQConstants.BUSINESS_EXCHANGE);
        rabbitMetaMessage.setRoutingKey(MQConstants.BUSINESS_KEY_TMC);
        rabbitMetaMessage.setPayload(JSON.toJSONString(map));
        try {
            rabbitSender.send(rabbitMetaMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("--- Leave shopReviewMessage(Long shopId) ---");
    }

    @Override
    public int update(Shop entity) {
        log.info("--- Enter update(Shop entity)，参数：{}", entity);
        Shop shop = this.getLatitudeAndLongitude(entity);
        if (shop == null){
            return -1;
        }

        int count = super.update(shop);
        if (count > 0 ) {
            if (entity.getCreateStatus() != null && entity.getCreateStatus() == 1){
                this.shopReviewMessage(entity.getShopId());
            }


        }
        log.info("--- Leave update(Shop entity)，返回值：{}", count);
        return count;
    }



    private void deleteFromFastDFS(List<String> pictures) {
        List<UploadFile> uploadFiles = new ArrayList<>();
        for (String picture : pictures) {
            UploadFile file = new UploadFile();
            file.setFilePath(picture);
            uploadFiles.add(file);
        }
        opcFileFeignApi.fileDelete(uploadFiles);
    }

    private Shop getLatitudeAndLongitude(Shop shop) {
        log.info("--- Enter getLatitudeAndLongitude(Shop shop)，参数：{} ---", shop);
        if (null != shop.getRegionProvinceId() && null != shop.getRegionCityId() && null != shop.getRegionCountyId() && null != shop.getAddress()) {
            String province = pmcFeignApi.getRegionNameByRegionId(shop.getRegionProvinceId()).getResult();
            String city = pmcFeignApi.getRegionNameByRegionId(shop.getRegionCityId()).getResult();
            String county = pmcFeignApi.getRegionNameByRegionId(shop.getRegionCountyId()).getResult();
            String str = province+city+county+shop.getAddress();
            Wrapper<Map> map = opcGaodeFeignApi.getLonLarByAddr(str, city);
            if (map.error()) {
                log.error("--- opcGaodeFeignApi.getLonLarByAddr(str, city)内部异常，参数：{}，{} ---",str,city);
                throw new OpcBizException(ErrorCodeEnum.GL99990002);
            }
            if (map.getResult() == null) {
                log.info("--- Leave opcGaodeFeignApi.getLonLarByAddr({}, {})，返回值：null ---",str,city);
                return  null;
            }
            Iterator<Map.Entry> iter = map.getResult().entrySet().iterator();
            String string = "";
            while (iter.hasNext()) {
                string = iter.next().getValue().toString();
            }
            if (string == "") {
                log.info("--- Leave opcGaodeFeignApi.getLonLarByAddr({}, {})，返回值：null ---",str,city);
                return null;
            }
            List<Double> location = Arrays.asList(string.split(",")).stream().map(l -> Double.parseDouble(l)).collect(Collectors.toList());
            shop.setLongitude(location.get(0));
            shop.setLatitude(location.get(1));
        }
        log.info("--- Leave getLatitudeAndLongitude(Shop shop)，返回值：{} ---", shop);
        return shop;
    }

    @Override
    public Shop findById(Long id) {
        System.out.println(id);
        log.info("findById={}",id);
        Shop shop = super.findById(id);
        Wrapper<UserInfoDto> userInfoDto = uacUserFeignApi.getUserInfoByUserId(shop.getUserId());
        if (userInfoDto.error()) {
            log.error("--- uacUserFeignApi.getUserInfoByUserId(shop.getUserId())内部异常，参数：{} ---", shop.getUserId());
            throw new UacBizException(ErrorCodeEnum.GL99990002);
        }
        shop.setUserName(userInfoDto.getResult().getUserName());
        List<ShopInfoDto> shopInfoDtos = new ArrayList<>();
        ShopInfoDto shopInfoDto = new ShopInfoDto();
        shopInfoDto.setShopId(shop.getShopId());
        shopInfoDto.setRegionCountryId(shop.getRegionCountryId());
        shopInfoDto.setRegionProvinceId(shop.getRegionProvinceId());
        shopInfoDto.setRegionCityId(shop.getRegionCityId());
        shopInfoDto.setRegionCountyId(shop.getRegionCountyId());
        shopInfoDtos.add(shopInfoDto);
        List<ShopInfoDto> shopInfos = pmcFeignApi.getRegionNameByRegionIds(shopInfoDtos);
        if (shopInfos == null || shopInfos.size() == 0) {
            log.error("--- pmcFeignApi.getRegionNameByRegionIds(shopInfoDtos)内部异常，参数：{} ---", shopInfoDtos);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        shop.setRegionProvinceName(shopInfos.get(0).getRegionProvinceName());
        shop.setRegionCityName(shopInfos.get(0).getRegionCityName());
        shop.setRegionCountyName(shopInfos.get(0).getRegionCountyName());
        return shop;
    }

    @Override
    public List<ShopDto> findShopsBySpecIds(List<Long> specIds) {
        return shopMapper.findShopsBySpecIds(specIds);
    }

    @Override
    public List<ShopDto> findNearShops(String longitude, String latitude,Integer deliverDistance) {
        //String转BigDecimal
        BigDecimal longitudeDecimal = new BigDecimal(longitude);
        BigDecimal latitudeDecimal = new BigDecimal(latitude);
        return shopMapper.findNearShops(longitudeDecimal, latitudeDecimal, deliverDistance);
    }

    @Override
    public List<ShopDto> findNearShopsBySpecIds(List<Long> specIds, String longitude, String latitude, Integer deliverDistance) {
        BigDecimal longitudeDecimal = new BigDecimal(longitude);
        BigDecimal latitudeDecimal = new BigDecimal(latitude);
        return shopMapper.findNearShopsBySpecIds(specIds, longitudeDecimal, latitudeDecimal, deliverDistance);
    }

    @Override
    public List<ShopDto> findShopsBySpecIdsAndDis(List<Long> specIds, String longitude, String latitude) {
        BigDecimal longitudeDecimal = new BigDecimal(longitude);
        BigDecimal latitudeDecimal = new BigDecimal(latitude);
        return shopMapper.findShopsBySpecIdsAndDis(specIds, longitudeDecimal, latitudeDecimal);
    }

    @Override
    public ShopDto getShopDtoByShopId(Long shopId) {
        return shopMapper.getShopDtoByShopId(shopId);
    }

    /*@Override
    public Map<Long, List<ShopDto>> findByIds(List<Long> shopIds) {
        List<ShopDto> shopDtos = shopMapper.findByIds(shopIds);
        Map<Long, List<ShopDto>> shops = new ArrayList<>();
        for (Long id : shopIds) {
            shops.put(id, shopDtos.stream().filter(shopDto -> shopDto.getShopId().equals(id)).collect(Collectors.toList()));
        }
        return shops;
    }*/

    @Override
    public List<ShopDto> findByIds(List<Long> shopIds) {
        List<ShopDto> shopDtoList = shopMapper.findByIds(shopIds);
        List<ShopDto> shopDtos = new ArrayList<>();
        for (Long shopId : shopIds) {
            for (ShopDto shopDto : shopDtoList) {
                if (shopId.equals(shopDto.getShopId())){
                    shopDtos.add(shopDto);
                }

            }
        }
        return shopDtos;
    }

    @Override
    public List<Shop> getListDetailByCondition(ShopDto shopDto) {
        log.info("--- Enter getListByCondition(Shop shop)，参数:{} ---", shopDto.toString());
        //获得groupId

        List<Shop> shops = shopMapper.getListDetailByCondition(shopDto);
        if (shops.size() == 0) {
            log.info("--- Leave getListByCondition(Shop shop)，返回值:{} ---", shops);
            return shops;
        }
        List<Long> userIds = shops.stream().map(Shop::getUserId).collect(Collectors.toList());
        Wrapper<List<UserInfoDto>> userInfoDtos = uacUserFeignApi.getUserInfoByUserIds(userIds);
        if (userInfoDtos.error()) {
            log.error("--- uacUserFeignApi.getUserInfoByUserIds(userIds)内部异常，参数：{} ---", userIds);
            throw new UacBizException(ErrorCodeEnum.GL99990002);
        }
        List<ShopInfoDto> shopInfoDtos = new ArrayList<>();
        for (Shop s:shops) {
            ShopInfoDto shopInfoDto = new ShopInfoDto();
            shopInfoDto.setShopId(s.getShopId());
            shopInfoDto.setRegionCountryId(s.getRegionCountryId());
            shopInfoDto.setRegionProvinceId(s.getRegionProvinceId());
            shopInfoDto.setRegionCityId(s.getRegionCityId());
            shopInfoDto.setRegionCountyId(s.getRegionCountyId());
            shopInfoDtos.add(shopInfoDto);
        }
        List<ShopInfoDto> list = pmcFeignApi.getRegionNameByRegionIds(shopInfoDtos);
        if (list == null || list.size() == 0) {
            log.error("--- pmcFeignApi.getRegionNameByRegionIds(shopInfoDtos)内部异常，参数：{} ---", shopInfoDtos);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        for (Shop s : shops) {
            for (UserInfoDto user : userInfoDtos.getResult()) {
                if (user.getUserId().equals(s.getUserId())) {
                    s.setUserName(user.getUserName());
                    s.setMobile(user.getMobile());
                }
            }
            for (ShopInfoDto shopInfoDto : list) {
                if (shopInfoDto.getShopId().equals(s.getShopId())) {
                    s.setRegionProvinceName(shopInfoDto.getRegionProvinceName());
                    s.setRegionCityName(shopInfoDto.getRegionCityName());
                    s.setRegionCountyName(shopInfoDto.getRegionCountyName());
                }
            }
        }
        log.info("--- Leave getListByCondition(Shop shop)，返回值:{} ---", shops.toArray());
        return shops;
    }

    @Override
    public List<ShopCartInfoDto> getShopCartInfoDto(List<GoodsAndSpecInfoDto> goodsAndSpecInfoDtos) {
        //TODO:有空需要优化
        List<ShopCartInfoDto> shopCartInfoDtos = shopMapper.getShopCartInfoDto(goodsAndSpecInfoDtos);
        List<Long> specIds = new ArrayList<>();
        // mod by wg 20190624，根据新的需求修改
//        for (ShopCartInfoDto shopCartInfoDto : shopCartInfoDtos) {
//            specIds.addAll(shopCartInfoDto.getGoodsAndSpecInfoDtos().stream().map(GoodsAndSpecInfoDto::getSpecId).collect(Collectors.toList()));
//        }

        for (GoodsAndSpecInfoDto goodsAndSpecInfoDto : goodsAndSpecInfoDtos) {
            specIds.add(goodsAndSpecInfoDto.getSpecId());
        }
        StringBuffer stringBuffer = new StringBuffer();
        int count = 0;
        for (Long specId : specIds) {
            stringBuffer.append(specId);
            count ++;
            if (specIds.size() != count) {
                stringBuffer.append(",");
            }
        }
        List<ProdSpecInfoDto> prodSpecInfoDtos = new ArrayList<>();
        prodSpecInfoDtos = pmcFeignApi.getSpecInfoDtosBySpecIds(stringBuffer.toString());
        if (prodSpecInfoDtos == null || prodSpecInfoDtos.size() < 1 ) {
            log.error("--- pmcFeignApi.getSpecInfoDtosBySpecIds(stringBuffer.toString())内部异常，参数：{} ---", stringBuffer.toString());
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        for (ShopCartInfoDto shopCartInfoDto : shopCartInfoDtos) {
            List<GoodsAndSpecInfoDto> goodsAndSpecInfoDtoList = shopCartInfoDto.getGoodsAndSpecInfoDtos();
            for (GoodsAndSpecInfoDto goodsAndSpecInfoDto : goodsAndSpecInfoDtoList) {
                for (ProdSpecInfoDto prodSpecInfoDto : prodSpecInfoDtos) {
                    if (goodsAndSpecInfoDto.getSpecId().equals(prodSpecInfoDto.getSpecId())) {
                        goodsAndSpecInfoDto.setSpecName(prodSpecInfoDto.getSpecName());
                        goodsAndSpecInfoDto.setPicture(prodSpecInfoDto.getPicture());
                        goodsAndSpecInfoDto.setWeight(prodSpecInfoDto.getWeight());
                    }
                }
                for (GoodsAndSpecInfoDto goodsAndSpecInfoDtoOld : goodsAndSpecInfoDtos) {
                    if (goodsAndSpecInfoDto.getSpecId().equals(goodsAndSpecInfoDtoOld.getSpecId())&&goodsAndSpecInfoDto.getShopId().equals(goodsAndSpecInfoDtoOld.getShopId())) {
                        goodsAndSpecInfoDto.setNum(goodsAndSpecInfoDtoOld.getNum());
                    }
                }
            }
//            shopCartInfoDto.getGoodsAndSpecInfoDtos().stream()
//                    .forEach(goodsAndSpecInfoDto -> {
//                        ProdSpecInfoDto prodSpecInfoDto = pmcFeignApi.getSpecInfoDtoBySpecId(goodsAndSpecInfoDto.getSpecId());
//                        goodsAndSpecInfoDto.setSpecName(prodSpecInfoDto.getSpecName());
//                        goodsAndSpecInfoDto.setPicture(prodSpecInfoDto.getPicture());
//                        goodsAndSpecInfoDto.setWeight(prodSpecInfoDto.getWeight());
//                        goodsAndSpecInfoDto.setNum(goodsAndSpecInfoDtos.stream().filter(g -> g.getSpecId().equals(goodsAndSpecInfoDto.getSpecId())&&g.getShopId().equals(goodsAndSpecInfoDto.getShopId())).map(g -> g.getNum()).collect(Collectors.toList()).get(0));
//                    });
        }
        return shopCartInfoDtos;
    }

    @Override
    public List<ShopInfoDto> getShopUserIdByShopIds(List<Long> shopIds) {
        return shopMapper.getShopInfoByShopIds(shopIds);
    }

    @Override
    public List<ShopInfoDto> getShopInfoByShopIds(List<Long> shopIds) {
        log.info("ShopServiceImpl.getShopInfoByShopIds={}",shopIds);
        if(shopIds==null || shopIds.get(0) == 0 ){
            shopIds.add(220854931912392704L);
        }

        List<ShopInfoDto> shopInfoDtos = shopMapper.getShopInfoByShopIds(shopIds);
       if (shopInfoDtos ==null && shopInfoDtos.size() == 0){
           log.info("ShopServiceImpl.getShopInfoByShopIds方法的shopInfoDtos值为空");
           return null;
       }
        List<Long> userIds = shopInfoDtos.stream().map(ShopInfoDto::getUserId).collect(Collectors.toList());

        Wrapper<List<UserInfoDto>> userInfoDtos = uacUserFeignApi.getUserInfoByUserIds(userIds);
        if (userInfoDtos.error()) {
            log.error("--- uacUserFeignApi.getUserInfoByUserIds(userIds)内部异常，参数：{} ---", userIds);
            throw new UacBizException(ErrorCodeEnum.GL99990002);
        }
        shopInfoDtos.forEach(shopInfoDto -> {
            Optional<UserInfoDto> userInfoDto = userInfoDtos.getResult().stream().filter(user -> user.getUserId().equals(shopInfoDto.getUserId())).findFirst();
            if (userInfoDto.isPresent()) {
                shopInfoDto.setUserName(userInfoDto.get().getUserName());
                shopInfoDto.setMobile(userInfoDto.get().getMobile());
            }
        });
        List<ShopInfoDto> shopInfos = pmcFeignApi.getRegionNameByRegionIds(shopInfoDtos);
        if (shopInfos ==  null || shopInfos.size() == 0) {
            log.error("--- pmcFeignApi.getRegionNameByRegionIds(shopInfoDtos)内部异常，参数：{} ---", shopInfoDtos);
            throw new PmcBizException(ErrorCodeEnum.GL99990002);
        }
        return shopInfos;
    }

    @Override
    public List<ShopInfoDto> getShopAccountByShopIds(List<Long> shopIds) {
        return shopMapper.getShopInfoByShopIds(shopIds);
    }

    @Override
    public List<ShopDto> findNearShopsAndReferenceShop(String longitude, String latitude, Integer deliverDistance, Long userId) {
        //String转BigDecimal
        BigDecimal longitudeDecimal = new BigDecimal(longitude);
        BigDecimal latitudeDecimal = new BigDecimal(latitude);

        Long referenceShopId = null; //173802084142415872L;//null;
        // 根据用户ID获取该用户对应的推荐店铺ID
        if (userId != null) {
            //先获取自己的店铺ID
            Example example = new Example(Shop.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId", userId);
            List<Shop> shops = shopMapper.selectByExample(example);
            if (shops != null && shops.size() > 0) {
                referenceShopId = shops.get(0).getShopId();
            }
            //自己没有店铺的，获取推荐人店铺
            if (referenceShopId == null || referenceShopId <= 0L) {
                Wrapper<UserInfoDto> userInfoDto = uacUserFeignApi.getUserInfoByUserId(userId);
                if (userInfoDto.error()) {
                    log.error("--- uacUserFeignApi.getUserInfoByUserId(shop.getUserId())内部异常，参数：{} ---", userId);
                    throw new SmcBizException(ErrorCodeEnum.GL99990002);
                }

                referenceShopId = userInfoDto.getResult().getReferenceShopId();
            }
        }

        return shopMapper.findNearShopsAndReferenceShop(longitudeDecimal, latitudeDecimal, deliverDistance, referenceShopId);
    }

    @Override
    public List<ShopDto> findNearSelfShops(String longitude, String latitude, Integer deliverDistance) {
        //String转BigDecimal
        BigDecimal longitudeDecimal = new BigDecimal(longitude);
        BigDecimal latitudeDecimal = new BigDecimal(latitude);

        return shopMapper.findNearSelfShops(longitudeDecimal, latitudeDecimal, deliverDistance);
    }

    @Override
    public ShopInfoDto getShopByFactoryId(Long factoryId) {
        Example example = new Example(Shop.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("factoryId", factoryId);
        List<Shop> listShop = shopMapper.selectByExample(example);

        ShopInfoDto shopInfoDto = new ShopInfoDto();
        if (listShop.size() > 0) {
            BeanUtils.copyProperties(listShop.get(0), shopInfoDto);
        }

        return  shopInfoDto;
    }

    @Override
    public List<ShopInfoDto> getShopIdsByCondition(Shop shop) {

        return shopMapper.getShopIdsByCondition(shop);
    }

    @Override
    public List<ShopInfoDto> getShopInfoDtoByUserId(Long userId) {

        return shopMapper.getShopDtoByUserId(userId);
    }

    @Override
    public List<ShopInfoDto> getShopInfoByShopName(String shopName) {

        List<ShopInfoDto> list =new ArrayList<>();
        list = shopMapper.getShopInfoByShopName(shopName);
//        Integer aa = shopName.length();
//        Integer i = 0;
//        while (i<aa){
//            i++;
//            if (shopName.length()>1){
//
//                list = shopMapper.getShopInfoByShopName(shopName);
//
//                if (list != null && list.size() > 0){
//                    break;
//                }else{
//                    shopName = shopName.substring(0,aa-i-1);
//
//                }
//            }
//        }

        return list;
    }

    @Override
    public List<ShopInfoDto> getShopInfoByGroupId(Long groupId) {
        return shopMapper.getShopInfoByGroupId(groupId);
    }

    @Override
    public List<ShopInfoDto> getShopInfoDtoByUserIdList(List<Long> userIds) {
        return shopMapper.getShopInfoDtoByUserIdList(userIds);
    }


    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    public Integer saveShop(ShopInfoDto record) {
        log.info("--- shop save begin:{} ---", record);

        // add by wg 20190805 增加判断，是否有店铺正在审核中，如果有则直接返回
        Shop shopApply = new Shop();
        shopApply.setUserId(record.getUserId());
        int applyCount = super.selectCount(shopApply);
        if (applyCount > 0) {
            log.info("--- 店铺已经在申请中 ---");
            return -3;
        }
        BeanUtils.copyProperties(record,shopApply);
        shopApply.setTelephone(record.getMobile());
        shopApply.setCreateStatus((byte) 2);
        shopApply.setRunStatus((byte) 1);
        shopApply.setShopId(generateId());
        shopApply.setOpenTime(480);
        shopApply.setCloseTime(1380);

        Integer count = super.save(shopApply);


        //todo 2019-12-06 让店铺绑定仓库
        SmcShopDto smcShopDto = new SmcShopDto();
        BeanUtils.copyProperties(record, smcShopDto);
        smcShopDto.setShopId(shopApply.getShopId());
        wmcStorageFeignApi.bindWarehouseShop(smcShopDto);

        //todo 2019-12-06 保存店铺资源
        shopApply.setWarehouseId(record.getWarehouseId());
        getShopIdToStore(shopApply);
        log.info("{}--- shop save end:{} ---",count, record);
        return count;
    }



    @Override
    public void getShopIdToStore(Shop shop) {

        //则根据手机号在shop表中查shopId
        Example example = new Example(DmsStore.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("telephone", shop.getTelephone());
        List<DmsStore> dmsStores = dmsStoreMapper.selectByExample(example);

        if (dmsStores.size() >0 ){
            DmsStore dmsStore = dmsStores.get(0);
            //即存入store中
            dmsStore.setShopId(shop.getShopId());
            dmsStoreMapper.updateByPrimaryKey(dmsStore);
            System.out.println("dmsStore=:"+dmsStore);
            //storeId 存入shop
            shop.setStoreId(dmsStores.get(0).getStoreId());
            shopMapper.updateByPrimaryKey(shop);
        }else{
            Example example2 = new Example(DmsStore.class);
            Example.Criteria criteria2 = example2.createCriteria();
            criteria2.andEqualTo("shopId", shop.getShopId());
            List<DmsStore> dmsStores2 = dmsStoreMapper.selectByExample(example2);
            if (dmsStores2 != null && dmsStores2.size() > 0){
                DmsStore dmsStore2 = dmsStores2.get(0);
                dmsStore2.setTelephone(shop.getTelephone());
                dmsStoreMapper.updateByPrimaryKey(dmsStore2);

                //storeId 存入shop
                shop.setStoreId(dmsStores.get(0).getStoreId());
                shopMapper.updateByPrimaryKey(shop);
            }else{
                if (shop.getWarehouseId() == null || shop.getWarehouseId() < 1){
                    Wrapper wrapper = wmcStorageFeignApi.getGroupIdByShopId(shop.getShopId());
                    if (wrapper.getCode()==200){
                        shop.setWarehouseId(Long.valueOf(wrapper.getResult().toString()));
                    }
                }

                Long storeId = saveStore(shop);
            }

        }
    }

    @Override
    public Long saveStore(Shop shop){
        //处理
        DmsStore dmsStore = new DmsStore();
        //dmsStore.setStoreId(generateId());
        dmsStore.setStoreName(shop.getShopName());
        dmsStore.setTelephone(shop.getTelephone());
        dmsStore.setProvinceId(shop.getRegionProvinceId());
        dmsStore.setCityId(shop.getRegionCityId());
        dmsStore.setCountyId(shop.getRegionCountyId());
        dmsStore.setAddress(shop.getAddress());
        dmsStore.setLongitude(shop.getLongitude());
        dmsStore.setLatitude(shop.getLatitude());
        dmsStore.setShopId(shop.getShopId());
        dmsStore.setWarehouseId(shop.getWarehouseId());
        dmsStore.setStoreType((byte)0);
        dmsStore.setStoreLevel((byte)0);
        dmsStore.setScopeId(99);
        dmsStoreMapper.insertSelective(dmsStore);

        return dmsStore.getStoreId();
    }

    @Override
    public  ShopInfoDto getShopInfoByShopId(Long shopId){
        return shopMapper.getShopInfoByShopId(shopId);
    }

    @Override
    public List<ShopInfoDto> getAllShopInfo() {
        return null;
    }

    @Override
    public List<StoreShopDto> findShopByStore(List<Long> storeIdList) {

        List<StoreShopDto> list = new ArrayList<>();

        long startTime = System.currentTimeMillis();
        for (Long storeId : storeIdList) {

            StoreShopDto dto = shopMapper.findShopByStore(storeId);

            list.add(dto);

        }
        long endTime = System.currentTimeMillis();

        System.out.println("程序运行时间：" + (endTime - startTime) + "ms");
        return list;
    }

    @Override
    public List<ShopInfoDto> findShopNameByShopIds(List<Long> shopIds) {
        return shopMapper.findShopNameByShopIds(shopIds);
    }

    @Override
    public Integer insertShop(Shop shop){
        return shopMapper.insertSelective(shop);
    }

    @Override
    public List<ShopDto> findNearShopTeam(String longitude, String latitude,Integer deliverDistance) {
        //String转BigDecimal
        BigDecimal longitudeDecimal = new BigDecimal(longitude);
        BigDecimal latitudeDecimal = new BigDecimal(latitude);
        return shopMapper.findNearShopTeam(longitudeDecimal, latitudeDecimal, deliverDistance);
    }

    @Override
    public List<ShopDto> findUsedShopTeam(Long userId) {
        Wrapper<UserInfoDto> userInfoDto = uacUserFeignApi.getUserInfoByUserId(userId);
        Long shopId = 0L;

        if (userInfoDto.getCode() == 200){

            if (userInfoDto.getResult().getReferenceShopId() > 0){

                shopId = userInfoDto.getResult().getReferenceShopId();
            }

        }
        List<ShopDto> shopDtoList = shopMapper.findUsedShopTeam(userId,shopId);

        return shopDtoList;
    }

    /**
     * 查询 两天未下单的加盟店铺
     * @return
     */
    @Override
    public  List<ExcelObject> joinExcel() {
        return shopMapper.joinExcel();
    }

    /**
     * 查询两天内 未下单的加盟店铺
     * @return
     */
    @Override
    public List<ExcelObject> activeShops() {
        return shopMapper.activeShops();
    }


}
